﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using HengTong.Model.Db;
using HengTong.Model.Db.Hr;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;


namespace HengTong.ViewModel.Person.SysPersonEducationVms
{
    public partial class SysPersonEducationVm : BaseCRUDVM<SysPersonEducation>
    {
        public List<SysPersonEducationFile> SelectedEducationFilesIds { get; set; }

        public SysPersonEducationVm()
        {
            SetInclude(x => x.Person);
        }

        protected override void InitVM()
        {
            if (Entity.HasID())
            {
                SelectedEducationFilesIds = DC.Set<SysPersonEducationFile>()
                    .Where(e => e.PersonEducationId == Entity.ID)
                    .ToList();
            }
        }

        public override async Task DoAddAsync()
        {
            // 验证学历附件
            if (Entity.EducationLevel > EducationLevel.高中)
            {
                if (SelectedEducationFilesIds == null || !SelectedEducationFilesIds.Any())
                {
                    MSD.AddModelError("SelectedEducationFilesIds", "学历大于高中时，必须上传学历附件");
                    return;
                }
            }

            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoAddAsync();
            if (SelectedEducationFilesIds.Any())
            {
                foreach (var item in SelectedEducationFilesIds)
                {
                    item.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
                    item.PersonEducationId = Entity.ID;
                    item.Order = item.Order;
                }

                await DC.Set<SysPersonEducationFile>().AddRangeAsync(SelectedEducationFilesIds);

                await DC.SaveChangesAsync();
            }
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            // 验证学历附件
            if (Entity.EducationLevel > EducationLevel.高中)
            {
                if (SelectedEducationFilesIds == null || !SelectedEducationFilesIds.Any())
                {
                    MSD.AddModelError("SelectedEducationFilesIds", "学历大于高中时，必须上传学历附件");
                    return;
                }
            }

            if (SelectedEducationFilesIds.Any())
            {
                //先删除原有的文件
                var existingFiles = DC.Set<SysPersonEducationFile>()
                    .Where(x => x.PersonEducationId == Entity.ID)
                    .ToList();
                if (existingFiles.Any())
                {
                    DC.Set<SysPersonEducationFile>().RemoveRange(existingFiles);
                }

                foreach (var item in SelectedEducationFilesIds)
                {
                    item.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
                    item.PersonEducationId = Entity.ID;
                    item.Order = item.Order;
                }

                await DC.Set<SysPersonEducationFile>().AddRangeAsync(SelectedEducationFilesIds);
                await DC.SaveChangesAsync();
            }

            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoEditAsync(updateAllFields);
        }

        public async Task ApproveAsync(bool upAllFields = false)
        {
            DC = Wtm.CreateDC();
            var transaction = DC.BeginTransaction();
            try
            {
                if (Entity is IFlow flow)
                {
                    flow.Approver = Wtm.LoginUserInfo?.ITCode;
                    flow.ApprovalTime = DateTime.Now;
                }

                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    await ContinueWorkflowAsync(ActionName, Remark);
                    await transaction.CommitAsync();
                }
                else
                {
                    await transaction.RollbackAsync();
                }
            }
            catch (Exception e)
            {
                // 回滚事务
                await transaction.RollbackAsync();
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
            finally
            {
                await transaction.DisposeAsync();
            }
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}